﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Library.Data.Security.Encryption;

namespace UnigenReport.Form
{
    public partial class ucPackingStandardEdit : UserControl
    {
        private PackingStandard refData;
        private UnigenDataContext db;
        private bool action;//True: Add, False: Update

        #region Thiết lập

        public ucPackingStandardEdit()
        {
            InitializeComponent();
            //Phân quyền
            if (Variables.UserRoleID == 0) btnSave.Enabled = false;
            SetEvent();

            action = true;
        }

        /// <summary>
        /// Hàm show ra ngoài cho việc update
        /// </summary>
        /// <param name="refData"></param>
        /// <returns></returns>
        public ucPackingStandardEdit ForUpdate(PackingStandard obj)
        {
            refData = obj;
            action = false;
            return this;
        }

        /// <summary>
        /// Khai báo các sự kiện
        /// </summary>
        private void SetEvent()
        {
            Load += OnLoad;
            this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
            this.btnCancel.Click += new System.EventHandler(this.btnCancel_Click);
            this.cboProduct.KeyDown += new System.Windows.Forms.KeyEventHandler(this.cboProduct_KeyDown);
        }
        
        /// <summary>
        /// Hàm load form
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnLoad(object sender, EventArgs e)
        {
            //Load default
            SetDefault();
        }
        
        /// <summary>
        /// Thiết lập các giá trị mặc định của form
        /// </summary>
        private void SetDefault()
        {
            db = new UnigenDataContext();
            //Product
            if(action)
                sourceProduct.DataSource = db.Products.Where(p => p.Active == true && p.PackingStandards.Count == 0).ToList();
            else
                sourceProduct.DataSource = db.Products.Where(p => p.Active == true && p.ProductId == refData.ProductId).ToList();

            //Carton type
            sourceCartonType.DataSource = db.CartonTypes.ToList();

            //Bind dữ liệu chính
            BindData();
        }

        /// <summary>
        /// Lấy dữ liệu chính
        /// </summary>
        private void BindData()
        {
            try
            {
                //Data bind
                if (refData != null)
                {
                    db = new UnigenDataContext();
                    pnlTitle.Text = "SỬA ĐỔI THÔNG TIN";

                    //Product
                    var selectedProduct = (sourceProduct.DataSource as List<Product>).SingleOrDefault(p => p.ProductId == refData.ProductId);
                    if (selectedProduct != null)
                        cboProduct.SelectedValue = selectedProduct.ProductId;

                    var selectedCarton = (sourceCartonType.DataSource as List<CartonType>).SingleOrDefault(p => p.CartonTypeId == refData.CartonTypeId);
                    if (selectedCarton != null)
                        cboCartonType.SelectedValue = selectedCarton.CartonTypeId;

                    txtQtyPerInnerBox.Value = refData.QtyPerInnerBox ?? 1;
                    txtWeightOfInnerBox.Value = refData.WeightOfInnerBox ?? 0;
                    txtQtyPerShippingBox.Value = refData.QtyPerShippingBox ?? 1;
                    txtWeightOfShippingBox.Value = refData.WeightOfShippingBox ?? 0;
                }
                else
                    pnlTitle.Text = "THÊM MỚI";
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("BindData - " + ex.Message);
            }
        }

        #endregion

        #region Hàm

        private void Save()
        {
            try
            {
                var product = Convert.ToInt32(cboProduct.SelectedValue ?? 0);
                var qtyPerInnerBox = (int)txtQtyPerInnerBox.Value;
                var weightOfInnerBox = txtWeightOfInnerBox.Value;
                var qtyPerShippingBox = (int)txtQtyPerShippingBox.Value;
                var weightOfShippingBox = txtWeightOfShippingBox.Value;

                #region Check valid
                if (product == 0)
                {
                    Common.ShowNoticeMess("Nhập mặt hàng!");
                    return;
                }
                #endregion

                db = new UnigenDataContext();
                var p = new PackingStandard();
                if (action)//Thêm mới
                {
                    p.ProductId = product;
	                p.QtyPerInnerBox = qtyPerInnerBox;
	                p.WeightOfInnerBox = weightOfInnerBox;
	                p.QtyPerShippingBox = qtyPerShippingBox;
	                p.WeightOfShippingBox = weightOfShippingBox;
                    p.CartonTypeId = (int?)cboCartonType.SelectedValue;
                    p.Active = true;

                    //Thêm thông tin
                    db.PackingStandards.InsertOnSubmit(p);
                }
                else
                {
                    //Cập nhật thông tin
                    p = db.PackingStandards.SingleOrDefault(pt => pt.PackingId == refData.PackingId);
                    if (p != null)
                    {
                        p.ProductId = product;
                        p.QtyPerInnerBox = qtyPerInnerBox;
                        p.WeightOfInnerBox = weightOfInnerBox;
                        p.QtyPerShippingBox = qtyPerShippingBox;
                        p.WeightOfShippingBox = weightOfShippingBox;
                        p.CartonTypeId = (int?)cboCartonType.SelectedValue;
                    }
                }

                //Xác nhận
                db.SubmitChanges();

                //Thông báo
                this.ParentForm.DialogResult = DialogResult.OK;
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("Save - " + ex.Message);
            }
        }

        #endregion

        #region Sự kiện

        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
           if (keyData == Keys.Enter && btnSave.Enabled == true && !btnSave.Focused && !btnCancel.Focused && (cboProduct.FocusedElement == null))
            {
                Save();
            }
            if (keyData == Keys.Escape)
            {
                this.ParentForm.DialogResult = DialogResult.Cancel;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void cboProduct_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                {
                    var selectedProduct = new Product();
                    var productId = 0;
                    if (int.TryParse(cboProduct.Text.Trim(), out productId))
                        selectedProduct = (sourceProduct.DataSource as List<Product>).SingleOrDefault(p => p.ProductId == productId);
                    else
                        selectedProduct = (sourceProduct.DataSource as List<Product>).FirstOrDefault(p => p.ProductName.Contains(cboProduct.Text.Trim()));

                    if (selectedProduct != null)
                        cboProduct.SelectedValue = selectedProduct.ProductId;
                    else
                        cboProduct.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                Common.ShowErrorMess("cboProduct_KeyDown - " + ex.Message);
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.ParentForm.DialogResult = DialogResult.Cancel;
        }
        #endregion
    }
}
